package com.junlong0716.enjoylearning.ui

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.widget.ImageView
import android.widget.TextView
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.htxcsoft.corelibrary.glide.GlideUtils
import com.junlong0716.enjoylearning.MyApp
import com.junlong0716.enjoylearning.R
import com.junlong0716.enjoylearning.adapter.ChannelListAdapter
import com.junlong0716.enjoylearning.constant.NetConstant
import com.junlong0716.enjoylearning.constant.NetConstant.REQUEST_SOURCE
import com.junlong0716.enjoylearning.entity.AudioEntity
import com.junlong0716.enjoylearning.entity.ChannelMultipleItemEntity
import com.junlong0716.enjoylearning.net.api.NetApi
import com.junlong0716.enjoylearning.service.MusicService
import com.junlong0716.enjoylearning.service.PlayerManager
import com.junlong0716.enjoylearning.widget.PlayerBarView
import com.junlong0716.getknowledgedemo.decoration.DividerItemNoEndDecoration
import com.junlong0716.module.common.rxbus.RxBus
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_topic.*
import org.json.JSONObject

class TopicActivity : AppCompatActivity(), BaseQuickAdapter.RequestLoadMoreListener {
    private lateinit var topicListAdapter: ChannelListAdapter
    private var topicId = 0
    private var topicName = ""
    private var topicImage = ""
    private var topicDescribe = ""
    private var topicPraiseNum = 0
    private var topicIsPraise = 0
    private lateinit var data: ArrayList<ChannelMultipleItemEntity>
    private var isLoadingMore = false
    private var currentPage = 1
    private var onePageCount = 10

    private var mPlayerBarView: PlayerBarView? = null
    private var musicService: MusicService? = null
    private var mPlayerManager: PlayerManager? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_topic)
        RxBus.getDefault().register(this)

        bindMusicService()

        topicId = intent.getIntExtra("TOPIC_ID", 0)
        topicIsPraise = intent.getIntExtra("TOPIC_IS_PRAISE", 0)
        topicName = intent.getStringExtra("TOPIC_NAME")
        topicImage = intent.getStringExtra("TOPIC_IMAGE")
        topicDescribe = intent.getStringExtra("TOPIC_DESCRIBE")
        topicPraiseNum = intent.getIntExtra("TOPIC_PRAISE_NUM", 0)


        if (topicIsPraise == 1) {
            //点赞成功
            iv_love.setImageResource(R.mipmap.ic_love_sel)
            tv_praise_num.text = (topicPraiseNum).toString()
            rl_praise.isClickable = false

        } else if (topicIsPraise == 0) {
            iv_love.setImageResource(R.mipmap.ic_love_unsel)
            tv_praise_num.text = (topicPraiseNum).toString()
            rl_praise.isClickable = true
        }

//        GlideUtils.showImage(this, REQUEST_SOURCE + topicImage, iv_topic_header_img)
//
//        toolbar.setNavigationIcon(R.drawable.ic_back)
//        toolbar.setNavigationOnClickListener { finish() }
        rl_back.setOnClickListener { finish() }
        tv_title.text = topicName
        data = ArrayList()
        topicListAdapter = ChannelListAdapter(data)
        rv_list.layoutManager = LinearLayoutManager(this)
        rv_list.adapter = topicListAdapter
        setOnRecyclerViewScrollDirectListener(rv_list)
        rv_list.addItemDecoration(DividerItemNoEndDecoration(this, DividerItemNoEndDecoration.VERTICAL_LIST, 3, ContextCompat.getColor(this, R.color.divider_gray)))
        topicListAdapter.setOnLoadMoreListener(this,rv_list)
        val topicHeader = LayoutInflater.from(this).inflate(R.layout.view_header_topic, null)
        val ivTopicHeader = topicHeader.findViewById<ImageView>(R.id.iv_topic_header)
        GlideUtils.showImage(this, REQUEST_SOURCE + topicImage, ivTopicHeader)

        val tvDescribe = topicHeader.findViewById<TextView>(R.id.tv_describe)
        tvDescribe.text = topicDescribe

        topicListAdapter.addHeaderView(topicHeader)

        requestTopicKnowledgeList()
        topicListAdapter.setOnItemClickListener { adapter, view, position ->
            when (data[position].knowledgeType) {
                1 -> {
                    val intent = Intent()
                    intent.setClass(this, VideoActivity::class.java)
                    intent.putExtra("video_url", NetConstant.REQUEST_SOURCE + data[position].fileAddress)
                    intent.putExtra("video_id", data[position].id)
                    intent.putExtra("video_author", data[position].authorName)
                    startActivity(intent)
                }
                2 -> {
                    val audioEntity = AudioEntity(data[position].id, REQUEST_SOURCE + data[position].fileAddress, data[position].knowledgeTitle, REQUEST_SOURCE + data[position].coverImg)
                    mPlayerManager!!.playMusic(audioEntity)
                }
                3 -> {
                    val intent = Intent()
                    intent.setClass(this, WebActivity::class.java)
                    intent.putExtra("document_url", NetConstant.REQUEST_SOURCE + data[position].fileAddress)
                    intent.putExtra("document_title", data[position].knowledgeTitle)
                    intent.putExtra("document_id", data[position].id)
                    startActivity(intent)
                }
                else -> {

                }
            }
        }



        rl_comment.setOnClickListener {
            val intent = Intent(this, TopicCommentActivity::class.java)
            intent.putExtra("topic_id", topicId)
            startActivity(intent)
            overridePendingTransition(R.anim.anim_up, 0)
        }



        rl_praise.setOnClickListener {

            if (topicIsPraise == 1) {
                return@setOnClickListener
            }
            val map = HashMap<String, Any>()
            map["userId"] = MyApp.instance().userAccount!!.id
            map["specialId"] = topicId
            val jsonObj = JSONObject(map)
            OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_TOPIC_ADD_PRAISE)
                    .tag(this)
                    .upJson(jsonObj)
                    .execute(object : StringCallback() {
                        override fun onSuccess(response: Response<String>?) {
                            val jsonObj = JSONObject(response!!.body())
                            val code = jsonObj.getString("code")
                            if (code == "200") {
                                //点赞成功
                                iv_love.setImageResource(R.mipmap.ic_love_sel)
                                tv_praise_num.text = (topicPraiseNum + 1).toString()
                                rl_praise.isClickable = false
                            }
                        }
                    })
        }


        iv_detail.setOnClickListener {
            val intent = Intent(this,TopicDetailActivity::class.java)
            intent.putExtra("TOPIC_TITLE",topicName)
            intent.putExtra("TOPIC_DETAIL",topicDescribe)
            startActivity(intent)
        }
    }

    private var conn = object : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName?) {

        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            val myBinder = service as (MusicService.MyBinder)
            musicService = myBinder.getService()
            mPlayerManager = musicService!!.getPlayerManager()
            mPlayerBarView = PlayerBarView(this@TopicActivity, mPlayerManager!!, coordinator_layout)
        }
    }

    private fun bindMusicService() {
        val intent = Intent(this, MusicService::class.java)
        bindService(intent, conn, AppCompatActivity.BIND_AUTO_CREATE)
    }

    private fun requestTopicKnowledgeList() {
        val map = HashMap<String, Any>()
        if (topicId == 0) {
            ToastUtils.showShort("查无此专题！")
            finish()
            return
        }
        map["currentPage"] = currentPage
        map["onePageCount"] = onePageCount
        map["specialId"] = topicId
        map["userId"] = MyApp.instance().userAccount!!.id
        val jsonObj = JSONObject(map)

        OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_QUERY_KNOWLEDGE_LIST)
                .tag(this)
                .upJson(jsonObj)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val jsonObject = JSONObject(response!!.body())
                        val code = jsonObject.getInt("code")
                        if (code == 200) {

                            if (isLoadingMore) {
                                val loadingMordData = ArrayList<ChannelMultipleItemEntity>()
                                val data = jsonObject.getJSONObject("data")
                                val jsonArray = data.getJSONArray("list")
                                for (i in 0 until jsonArray.length()) {
                                    val id = jsonArray.getJSONObject(i).getInt("id")
                                    val knowledgeType = jsonArray.getJSONObject(i).getInt("knowledgeType")
                                    val knowledgeTitle = jsonArray.getJSONObject(i).getString("knowledgeTitle")
                                    val knowledgeContent = jsonArray.getJSONObject(i).getString("knowledgeContent")
                                    val knowledgeDescribe = jsonArray.getJSONObject(i).getString("knowledgeDescribe")
                                    val knowledgeAuthor = jsonArray.getJSONObject(i).getString("knowledgeAuthor")
                                    val coverImg = jsonArray.getJSONObject(i).getString("coverImg")
                                    val fileAddress = jsonArray.getJSONObject(i).getString("fileAddress")
                                    val browseNumber = jsonArray.getJSONObject(i).getString("browseNumber")
                                    val praiseNumber = jsonArray.getJSONObject(i).getInt("praiseNumber")
                                    val commentNumber = jsonArray.getJSONObject(i).getString("commentNumber")
                                    val specialId = jsonArray.getJSONObject(i).getString("specialId")
                                    val createDate = jsonArray.getJSONObject(i).getLong("createDate")
                                    val remarks = jsonArray.getJSONObject(i).getString("remarks")
                                    val authorName = jsonArray.getJSONObject(i).getString("authorName")
                                    loadingMordData.add(ChannelMultipleItemEntity(id, knowledgeType, knowledgeTitle, knowledgeDescribe
                                            , knowledgeContent, knowledgeAuthor, coverImg, praiseNumber, fileAddress, browseNumber,
                                            commentNumber, specialId, createDate, authorName, ""))
                                }

                                if (loadingMordData.isEmpty()) {
                                    topicListAdapter.loadMoreEnd()
                                    return
                                }
                                topicListAdapter.addData(loadingMordData)
                                topicListAdapter.loadMoreComplete()

                            } else {
                                this@TopicActivity.data.clear()
                                val data = jsonObject.getJSONObject("data")
                                val jsonArray = data.getJSONArray("list")
                                for (i in 0 until jsonArray.length()) {
                                    val id = jsonArray.getJSONObject(i).getInt("id")
                                    val knowledgeType = jsonArray.getJSONObject(i).getInt("knowledgeType")
                                    val knowledgeTitle = jsonArray.getJSONObject(i).getString("knowledgeTitle")
                                    val knowledgeContent = jsonArray.getJSONObject(i).getString("knowledgeContent")
                                    val knowledgeDescribe = jsonArray.getJSONObject(i).getString("knowledgeDescribe")
                                    val knowledgeAuthor = jsonArray.getJSONObject(i).getString("knowledgeAuthor")
                                    val coverImg = jsonArray.getJSONObject(i).getString("coverImg")
                                    val fileAddress = jsonArray.getJSONObject(i).getString("fileAddress")
                                    val browseNumber = jsonArray.getJSONObject(i).getString("browseNumber")
                                    val praiseNumber = jsonArray.getJSONObject(i).getInt("praiseNumber")
                                    val commentNumber = jsonArray.getJSONObject(i).getString("commentNumber")
                                    val specialId = jsonArray.getJSONObject(i).getString("specialId")
                                    val createDate = jsonArray.getJSONObject(i).getLong("createDate")
                                    val remarks = jsonArray.getJSONObject(i).getString("remarks")
                                    val authorName = jsonArray.getJSONObject(i).getString("authorName")
                                    this@TopicActivity.data.add(ChannelMultipleItemEntity(id, knowledgeType, knowledgeTitle, knowledgeDescribe
                                            , knowledgeContent, knowledgeAuthor, coverImg, praiseNumber, fileAddress, browseNumber,
                                            commentNumber, specialId, createDate, authorName, ""))
                                }
                                if (this@TopicActivity.data.isEmpty()) {
                                    topicListAdapter.emptyView = LayoutInflater.from(this@TopicActivity).inflate(R.layout.view_empty, null)
                                }
                                topicListAdapter.notifyDataSetChanged()
                            }
                        }
                    }
                })
    }




    override fun onLoadMoreRequested() {
        isLoadingMore = true
        currentPage += 1
        requestTopicKnowledgeList()
    }

    override fun onDestroy() {
        super.onDestroy()

        if (RxBus.getDefault().isRegistered(this)) {
            RxBus.getDefault().unregister(this)
        }

        mPlayerBarView = null
        unbindService(conn)
    }

    private fun setOnRecyclerViewScrollDirectListener(rvList: RecyclerView) {
        rvList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
                if (dy > 0) {
                    //todo 隐藏播放布局
                    if (Math.abs(dy) > 2) {
                        mPlayerBarView!!.setPlayerBarVisibility(false)
                    }

                } else {
                    //todo 显示播放布局
                    if (Math.abs(dy) > 2) {
                        mPlayerBarView!!.setPlayerBarVisibility(true)
                    }
                }
            }
        })
    }
}
